<template>
	<view class="container" @reach-bottom="onReachBottom">
		<!-- 头部导航 -->
		<myHeader title="我的账户" showBack />

		<!-- 标签栏 -->
		<!-- <view class="tab-bar">
      <view class="tab-item {{currentTab === 'pending' ? 'active' : ''}}" @tap="switchTab" data-tab="pending">悬赏中</view>
      <view class="tab-item {{currentTab === 'received' ? 'active' : ''}}" @tap="switchTab" data-tab="received">已接单</view>
      <view class="tab-item {{currentTab === 'completed' ? 'active' : ''}}" @tap="switchTab" data-tab="completed">已结单</view>
    </view> -->

		<!-- 金额卡片 -->
		<view class="amount-box">
			<view class="amount-item" v-for="(item, index) in userInfo.brokerages" :key="index"
				@click="navigateToWithdrawRecords(item.lang)">
				<view class="amount">{{ item.lang == "zh" ? "¥" : "$"
		      }}{{ (item.brokeragePrice || 0) / 100 }}</view>
				<view class="amount-label">可提金额
					<text class="item-arrow">></text>
				</view>
				<button class="withdraw-btn" @tap.stop="handleWithdraw(item)">提现</button>
			</view>
		</view>

		<!-- 邀请链接 -->
		<view class="invite-link-card">
			<view class="link-content">
				<text class="link-text">邀请链接: {{userInfo.inviterUrl}}</text>
			</view>
			<button class="copy-btn" @tap="copyLink">复制链接</button>
		</view>

		<!-- 佣金列表 -->
		<view class="commission-list">
			<block v-for="(item, index) in records" :key="index">
				<view class="list-item">
					<image class="user-avatar" :src="item.sourceUserInfo.avatar"></image>
					<view class="user-info">
						<text class="user-name">{{item.sourceUserInfo.nickname}}</text>
						<text class="user-type">{{item.sourceUserInfo.groups}}</text>
					</view>
					<view class="commission-info">
						<text class="commission-amount">{{(item.price||0)/100}}</text>
						<text class="commision-title">{{item.title}}</text>
						<text class="commission-time">{{ formatDate(item.createTime) }}</text>
					</view>
				</view>
			</block>

			<!-- 无更多数据提示 -->
			<view v-if="!page.hasMore" class="no-more-data">
				<text>没有更多数据了</text>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		brokerageRecords,
		applyWithdraw,
		getUserInfo
	} from "@/api"
	import {
		formatDate
	} from "@/utils/util";
	import myHeader from "@/component/header";
	export default {
		components: {
			myHeader,
		},
		data() {
			return {
				userInfo: {},
				currentTab: 'received', // 默认选中已接单
				page: {
					pageNo: 1,
					pageSize: 5,
					total: 0,
					hasMore: true // 添加是否有更多数据的标识
				},
				records: [],
				// 添加加载状态
				isWithdrawing: false
			};
		},
		onShow() {
			// 获取用户信息
			this.userInfo = uni.getStorageSync('userInfo');
			this.refreshCommissionList()
		},
		methods: {
			// 切换标签
			switchTab(e) {
				this.currentTab = e.currentTarget.dataset.tab;
				this.page.pageNo = 1; // 切换标签时重置页码
				this.records = []; // 清空数据
				this.getBrokerageRecords();
			},
			// 处理提现
			handleWithdraw(item) {
				const availableAmount = item.brokeragePrice || 0;

				// 弹出提现申请弹窗
				uni.showModal({
					title: '申请提现',
					placeholderText: `请输入提现金额`,
					editable: true,
					inputPlaceholder: '例如：100 或 100.5',
					inputType: 'number', // 限制输入为数字键盘
					success: async (res) => {
						if (res.confirm) {
							const inputAmount = res.content.trim();

							// 验证输入有效性
							if (!this.validateAmount(inputAmount)) {
								uni.showToast({
									title: '金额格式错误（仅支持数字，最多1位小数）',
									icon: 'none',
									duration: 2000
								});
								return;
							}

							// 转换为分（避免浮点数精度问题）
							const amountInCents = Math.round(parseFloat(inputAmount) * 100);

							// 调用提现接口
							await this.submitWithdrawal(amountInCents, item.lang);
						}
					}
				});
			},
			// 金额验证方法
			validateAmount(amountStr) {
				// 允许整数或一位小数（如：100、100.5）
				const regex = /^(\d+)(\.\d{1})?$/;
				return regex.test(amountStr) && parseFloat(amountStr) > 0;
			},
			// 提交提现申请（新增方法）
			async submitWithdrawal(amount, lang) {
				if (this.isWithdrawing) return; // 防止重复提交

				this.isWithdrawing = true;
				try {
					// 调用提现接口（假设接口需要金额、账户信息等参数）
					const res = await applyWithdraw({
						price: amount,
						lang: lang
					});

					if (res) {
						// uni.showToast({
						// 	title: '提现申请提交成功',
						// 	icon: 'success',
						// 	duration: 2000
						// });
						// // 刷新提现记录
						// this.getBrokerageRecords();
						// 在 submitWithdrawal 的 success 回调中修改为：
						uni.showModal({
							title: '提示',
							content: '提现申请提交成功',
							showCancel: false, // 隐藏取消按钮
							confirmText: '确定',
							success: async (res) => {
								if (res.confirm) {
									this.refreshUserInfo();
									// 用户点击确定后再刷新数据
									this.refreshCommissionList();
								}
							}
						});
					} else {
						uni.showToast({
							title: res.message || '提现申请失败',
							icon: 'none',
							duration: 2000
						});
					}
				} catch (error) {
					console.error('提现失败:', error);
					uni.showToast({
						title: error.msg||'网络异常，请稍后重试',
						icon: 'none',
						duration: 2000
					});
				} finally {
					this.isWithdrawing = false;
				}
			},

			// 复制链接
			copyLink() {
				uni.setClipboardData({
					data: this.userInfo.inviterUrl,
					success: () => {
						uni.showToast({
							title: '链接已复制',
							icon: 'success'
						});
					}
				});
			},
			// 查询分销记录
			async getBrokerageRecords() {
				if (!this.page.hasMore) return; // 如果没有更多数据则不请求

				const res = await brokerageRecords({
					pageNo: this.page.pageNo,
					pageSize: this.page.pageSize,
					lang: 'zh'
				});
				// 更新数据
				this.records = [...this.records, ...res.list];
				this.page.total = res.total;
				this.page.hasMore = this.records.length < res.total;
				this.page.pageNo++;
			},
			// 上拉加载更多
			onReachBottom() {
				this.getBrokerageRecords();
			},
			formatDate(time, format) {
				return formatDate(time, format);
			},
			//跳转到提现记录页面
			navigateToWithdrawRecords(lang) {
				uni.navigateTo({
					url: `/pages/my/brokerage/records?lang=` + lang,
				});
			},
			refreshCommissionList() {
				this.records = [];
				this.page.pageNo = 1;
				this.page.hasMore = true;
				this.getBrokerageRecords();
			},
			//刷新用户缓存
			async refreshUserInfo(){
				let res = await getUserInfo();
				if (res) {
					uni.setStorageSync("userInfo", res);
				}
				this.userInfo = {
					...res
				};
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		background-color: #141a2e;
		/* 深蓝色背景 */
		min-height: 100vh;
		/* 覆盖整个屏幕高度 */
	}

	.title {
		font-size: 36rpx;
		font-weight: 500;
	}

	.back-icon image {
		width: 40rpx;
		height: 40rpx;
	}

	/* 标签栏 */
	.tab-bar {
		display: flex;
		justify-content: space-around;
		padding: 20rpx 0;
		border-bottom: 1rpx solid rgba(255, 255, 255, 0.1);
	}

	.tab-item {
		color: rgba(255, 255, 255, 0.6);
		font-size: 28rpx;
		position: relative;
		padding: 0 20rpx;
	}

	.tab-item.active {
		color: #fff;
		font-weight: 500;
	}

	.tab-item.active::after {
		content: '';
		position: absolute;
		bottom: -10rpx;
		left: 50%;
		transform: translateX(-50%);
		width: 40rpx;
		height: 4rpx;
		background-color: #3a86ff;
		border-radius: 2rpx;
	}

	// 金额统计区域样式
	.amount-box {
		display: flex;
		justify-content: space-between;
		padding: 0 32rpx;
		margin-bottom: 16rpx;

		.amount-item {
			width: 326rpx;
			height: 214rpx;
			background-color: #fff;
			border-radius: 16rpx;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;

			.amount {
				font-size: 36rpx;
				font-weight: bold;
				color: #f85c02;
				margin-bottom: 7rpx;
			}

			.amount-label {
				font-size: 28rpx;
				color: #333333;
			}
		}
	}

	.amount-text {
		font-size: 48rpx;
		font-weight: bold;
		color: #ff6b00;
	}

	.usd-amount {
		color: #3a86ff;
	}

	.amount-desc {
		font-size: 24rpx;
		color: #999;
		margin-top: 10rpx;
		display: block;
	}

	.withdraw-btn {
		width: 144rpx;
		height: 56rpx;
		background: linear-gradient(90deg, #2F7FB9 0%, #045FB2 100%);
		border-radius: 4rpx 4rpx 4rpx 4rpx;
		font-size: 24rpx;
		color: #fff;
		margin-top: 20rpx;
		border: none;
	}

	/* 邀请链接 */
	.invite-link-card {
		background-color: #fff;
		border-radius: 4rpx;
		border: 2rpx solid #DCDFE6;
		margin: 30rpx;
		padding: 30rpx;
		display: flex;
		flex-direction: column;
		/* 添加此行，使内容垂直排列 */
		align-items: flex-start;
		/* 添加此行，使内容靠左对齐 */
		height: auto;
		/* 修改为auto，让内容决定高度 */

		.link-content {
			flex: 1;
			width: 100%;
			/* 确保文本容器占满宽度 */
		}

		.link-text {
			font-size: 32rpx;
			color: #333;
			line-height: 1.5;
			word-wrap: break-word;
			/* 添加此行，允许长单词断行 */
			word-break: break-all;
			/* 添加此行，强制断行 */
		}

		.copy-btn {
			width: 147rpx;
			height: 56rpx;
			background: linear-gradient(90deg, #2F7FB9 0%, #045FB2 100%);
			border-radius: 4rpx 4rpx 4rpx 4rpx;
			font-size: 24rpx;
			text-align: left;
			color: #fff;
			margin-top: 20rpx;
			border: none;
			margin-left: 0;
		}
	}

	/* 佣金列表 */
	.commission-list {
		padding: 0 30rpx;

		.commision-title {
			font-size: 28rpx;
			padding: 4rpx 12rpx;
			border-radius: 8rpx;
		}
	}

	.list-item {
		background-color: #fff;
		border-radius: 16rpx;
		padding: 24rpx 30rpx;
		display: flex;
		align-items: center;
		margin-bottom: 20rpx;
	}

	.user-avatar {
		width: 80rpx;
		height: 80rpx;
		border-radius: 8rpx;
		margin-right: 20rpx;
	}

	.user-info {
		flex: 1;
	}

	.commission-info {
		flex: 2;
		/* 分配剩余空间（根据实际需求调整比例） */
		display: flex;
		/* 启用 Flex 布局 */
		flex-direction: column;
		/* 子元素垂直排列 */
		text-align: right;
	}

	.user-name {
		font-size: 28rpx;
		color: #333;
		display: block;
	}

	.user-type {
		font-size: 24rpx;
		color: #999;
		margin-top: 4rpx;
	}

	.commission-amount {
		font-size: 32rpx;
		color: #ff6b00;
		font-weight: 500;
		margin-right: 20rpx;
	}

	.commission-time {
		font-size: 24rpx;
		color: #999;
	}
	.no-more-data {
		text-align: center;
		padding: 30rpx 0;
		color: #A0A4B7;
		font-size: 28rpx;
	}
</style>